/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package android.reasons;

import android.app.AlertDialog;
import android.app.ContextoAndroid;
import android.app.CustomListViewAdapter;
import android.app.Fragment;
import android.app.Mensaje;
import android.app.ProgressDialog;
import android.app.RowItem;
import android.content.DialogInterface;
import android.entidades.Data;
import android.entidades.Pensamiento;
import android.entidades.Voz;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.sql.UsuarioPensamiento;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.web.service.IPServer;
import android.web.service.WebService;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Locale;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

/**
   * Fragment that appears in the "content_frame", shows a planet
   */
  public class ViewFragment extends Fragment implements OnTouchListener, TextToSpeech.OnInitListener
  {
      private TextToSpeech textToSpeech;
      private ListView lv;
      private TextView header;
      protected static String valor;
      private ArrayList<RowItem> rowItems = new ArrayList<RowItem>();
      private ArrayList<UsuarioPensamiento> data;
      private GestureDetector gestureDetector;
        
      public ViewFragment() {
          // Empty constructor required for fragment subclasses
      }
 
     @Override
      public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
      {
        
        gestureDetector = new GestureDetector(ContextoAndroid.context, new GestureListener());
        View rootView = inflater.inflate(R.layout.home, container, false);
        lv = (ListView)rootView.findViewById(R.id.lvRazones);
        header = (TextView)rootView.findViewById(R.id.tvHomeWall);
        header.setText(valor);
        String headerText = "100+ Razones Que Hacen a "+ContextoAndroid.usuario.nombre+" Alguien Especial";
        header.setText(headerText);
        fillList();
        lv.setOnTouchListener(this);
       
        Typeface font = Typeface.createFromAsset(ContextoAndroid.context.getAssets(), "abril.ttf");
        ((TextView)rootView.findViewById(R.id.tvHomeWall)).setTypeface(font);
        textToSpeech = new TextToSpeech(ContextoAndroid.context, this);
        
        
        lv.setOnItemLongClickListener(new OnItemLongClickListener() {

            public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
                    final int pos, long id) {
                new AlertDialog.Builder(ContextoAndroid.context)
                    .setIcon(android.R.drawable.ic_dialog_alert)
                    .setTitle(R.string.eliminar)
                    .setMessage(R.string.borrar)
                    .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) 
                        {
                            
                                String ID = rowItems.get(pos).getIdServer();
                                new WebPetition().execute(ID);
                                UsuarioPensamiento u = new UsuarioPensamiento();
                                u.delete(ID);
                                str = ID;
                                Data.decreaseID();
                                refillList();
                               
                        }

                    })
                    .setNegativeButton(R.string.no, null)
                    .show(); 

                return true;
            }
        }); 
        
        return rootView;
      }
    
    private void fillList()
    {
        rowItems.clear();
        data = Pensamiento.readData();
        for (int i = data.size()-1; i >=0; i--) 
        {
            String http = IPServer.fullServer+"Fotos/uploads/thumbs/"+data.get(i).Foto;
            RowItem item = new RowItem(http, "Razón #"+(i+1), data.get(i).Pensamiento,data.get(i).IdServer);
            rowItems.add(item);
        }
        CustomListViewAdapter adapter = new CustomListViewAdapter(ContextoAndroid.context,R.layout.listitem, rowItems);
        lv.setAdapter(adapter); 
    }
    
    private void refillList()
    {
        rowItems.clear();
        for(int x=0;x<data.size();x++)
        {
            if(data.get(x).IdServer.equals(str))
            {
                data.remove(data.get(x));
                break;
            }
        }
        for (int i = data.size()-1; i >=0; i--) 
        {
            String http = IPServer.fullServer+"Fotos/uploads/thumbs/"+data.get(i).Foto;
            RowItem item = new RowItem(http, "Razón #"+(i+1), data.get(i).Pensamiento,data.get(i).IdServer);
            rowItems.add(item);
        }
        CustomListViewAdapter adapter = new CustomListViewAdapter(ContextoAndroid.context,R.layout.listitem, rowItems);
        lv.setAdapter(adapter); 
    }
      
    private void convertTextToSpeech(String text) 
    {
        if (null == text || "".equals(text)) {
           text = "Please give some input.";
        }
        if(Voz.getVoz().equals("1"))
            textToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH, null);
    }
    
    
    @Override
     public void onDestroy() {
         super.onDestroy();
        textToSpeech.shutdown();
     }
  
    
   
    String str;
    int position;
    
    @Override
    public void onInit(int status) 
    {
        if (status == TextToSpeech.SUCCESS) 
        {
            Locale loc = new Locale("es", "MX");
            int result = textToSpeech.setLanguage(loc);
            if (result == TextToSpeech.LANG_MISSING_DATA  || result == TextToSpeech.LANG_NOT_SUPPORTED) 
            {
                Mensaje.Mostrar("Error de voz :(" );
            } 
            else 
            {
                
            }
        } 
        else 
        {
            Mensaje.Mostrar("la Voz fallo :( !");
        }
    }

    public boolean onTouch(View arg0, MotionEvent arg1) {
        //Single Tap
        int adapterIndex = lv.pointToPosition((int) arg1.getX(),(int) arg1.getY());
        position = adapterIndex;
        return gestureDetector.onTouchEvent(arg1);
    }
    
    private class GestureListener extends GestureDetector.SimpleOnGestureListener {

            @Override
            public boolean onSingleTapConfirmed(MotionEvent e)
            {
                if(position>=0)
                {
                    String voice = rowItems.get(position).getDesc();
                    convertTextToSpeech(voice);
                }
                return true;
            }
        
         
    }
    private class WebPetition extends AsyncTask<String, Integer, Boolean> {
        
        ProgressDialog dialog;
        
        @Override
        protected void onPreExecute() {
            dialog = new ProgressDialog(ContextoAndroid.context);
            dialog.setIndeterminate(false);
            dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            dialog.setCancelable(true);
            dialog.setMessage("Borrando...");
            dialog.show();
        }
        @Override
        protected Boolean doInBackground(String... params) 
        {
            ArrayList<NameValuePair> lst = new ArrayList<NameValuePair>();
            lst.add(new BasicNameValuePair("ID",params[0]));
            WebService.HttpPost(lst, "Controladores/deleteRazon.php");
            return true;
        }

        @Override
        protected void onPostExecute(Boolean result) 
        {
            dialog.dismiss();
            if(result)
            {
                Mensaje.Mostrar("Se Ha Borrado");
            }
            else Mensaje.Mostrar("Ha Ocurrido un Error...");
        }
        @Override
        protected void onProgressUpdate(Integer... values) 
        {
            dialog.setMessage("Borrando...");
            dialog.setProgress(values[0]);
        }
    }
  }